package com.zhoug.map.data.database;

import android.annotation.SuppressLint;
import android.app.Application;

import com.zhoug.map.data.database.dao.BoundaryDao;
import com.zhoug.map.data.database.dao.CityDao;
import com.zhoug.map.data.database.entities.Boundary;
import com.zhoug.map.data.database.entities.City;

import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;

/**
 * 地图数据库
 * @Author 35574
 * @Date 2021/9/17
 * @Description
 */
@Database(version = MapDatabase.VERSION_CODE, entities = {City.class, Boundary.class}
)
public abstract class MapDatabase extends RoomDatabase {
    private static final String TAG = ">>>MapDatabase";
    public static final int VERSION_CODE = 1;
    private static final String DATABASE_NAME = "mapDatabase.db";
    private static MapDatabase singleInstance;
    private static Application application;

    public static void init(Application application) {
        MapDatabase.application = application;
    }

    @SuppressLint("PrivateApi")
    private static Application _getApplication() {
        if (application == null) {
            synchronized (Application.class) {
                if (application == null) {
                    try {
                        Class<?> activityThread = Class.forName("android.app.ActivityThread");
                        Object thread = activityThread.getMethod("currentActivityThread").invoke(null);
                        Object app = activityThread.getMethod("getApplication").invoke(thread);
                        if (app != null) {
                            application = (Application) app;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return application;
    }

    /**
     * 获取数据库实例
     * @return
     */
    public static MapDatabase getInstance() {
        if (null == singleInstance) {
            synchronized (MapDatabase.class) {
                if (null == singleInstance) {
                    singleInstance = Room.databaseBuilder(_getApplication(), MapDatabase.class, DATABASE_NAME)
                            .fallbackToDestructiveMigration()
                            .build();
                }
            }
        }
        return singleInstance;
    }


    public abstract CityDao getCityDao();

    public abstract BoundaryDao getBoundaryDao();

}
